package com.example.soapserver.service.impl;

import com.example.soapserver.model.user.*;
import com.example.soapserver.service.UserWebService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.jws.WebService;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户WebService服务实现
 */
@Service
@WebService(serviceName = "UserService",
           endpointInterface = "com.example.soapserver.service.UserWebService",
           targetNamespace = "http://com.cssc.cn/webservice/user")
public class UserWebServiceImpl implements UserWebService {

    private static final String DEFAULT_PASSWORD = "123456"; // 默认密码
    
    @Override
    public ReceiveUserDataResponse receiveUserData(ReceiveUserDataRequest request) {
        ReceiveUserDataResponse response = new ReceiveUserDataResponse();
        List<FailDetail> failDetails = new ArrayList<>();
        
        try {
            if (request == null || request.getUserData() == null) {
                response.setResultCode("ERROR");
                response.setResultMessage("请求数据不能为空");
                return response;
            }
            
            List<User> users = request.getUserData().getACCOUNT();
            if (users == null || users.isEmpty()) {
                response.setResultCode("ERROR");
                response.setResultMessage("用户数据不能为空");
                return response;
            }
            
            int successCount = 0;
            int failCount = 0;
            
            for (User user : users) {
                try {
                    // 数据验证
                    String validationError = validateUserData(user);
                    if (validationError != null) {
                        failCount++;
                        addFailDetail(failDetails, user, validationError);
                        continue;
                    }
                    
                    // 处理密码逻辑
                    processUserPassword(user);
                    
                    // 这里实现业务逻辑，如保存到数据库
                    boolean success = saveOrUpdateUser(user);
                    
                    if (success) {
                        successCount++;
                    } else {
                        failCount++;
                        addFailDetail(failDetails, user, "保存用户数据失败");
                    }
                    
                } catch (Exception e) {
                    failCount++;
                    addFailDetail(failDetails, user, "系统错误: " + e.getMessage());
                }
            }
            
            response.setResultCode("SUCCESS");
            response.setResultMessage("用户数据处理完成");
            response.setSuccessCount(successCount);
            response.setFailCount(failCount);
            
            if (!failDetails.isEmpty()) {
                FailDetailList failDetailList = new FailDetailList();
                response.setFailDetails(failDetailList);
            }
            
        } catch (Exception e) {
            response.setResultCode("ERROR");
            response.setResultMessage("系统错误: " + e.getMessage());
        }
        
        return response;
    }
    
    @Override
    public GetUserResponse getUser(GetUserRequest request) {
        GetUserResponse response = new GetUserResponse();
        
        try {
            if (request == null || !StringUtils.hasText(request.getUserCode())) {
                response.setResultCode("ERROR");
                response.setResultMessage("用户编码不能为空");
                return response;
            }
            
            // 这里实现从数据库查询的逻辑
            User user = findUserByCode(request.getUserCode());
            
            if (user != null) {
                // 敏感信息处理，不返回密码
                user.setUSERPASSWORD(null);
                response.setUser(user);
                response.setResultCode("SUCCESS");
                response.setResultMessage("查询成功");
            } else {
                response.setResultCode("NOT_FOUND");
                response.setResultMessage("未找到对应的用户信息");
            }
            
        } catch (Exception e) {
            response.setResultCode("ERROR");
            response.setResultMessage("查询失败: " + e.getMessage());
        }
        
        return response;
    }
    
    @Override
    public UserLoginResponse userLogin(UserLoginRequest request) {
        UserLoginResponse response = new UserLoginResponse();
        
        try {
            if (request == null || !StringUtils.hasText(request.getUserCode()) || 
                !StringUtils.hasText(request.getPassword())) {
                response.setResultCode("ERROR");
                response.setResultMessage("用户名和密码不能为空");
                response.setLoginResult(false);
                return response;
            }
            
            // 这里实现用户登录验证逻辑
            User user = authenticateUser(request.getUserCode(), request.getPassword());
            
            if (user != null) {
                // 检查用户状态
                if (user.getUSERSTATUS() != null && user.getUSERSTATUS() == 0) {

                    response.setResultCode("USER_DISABLED");
                    response.setResultMessage("用户已被禁用");
                    response.setLoginResult(false);
                } else if (user.getACCSTATUS() != null && user.getACCSTATUS() == 0) {
                    response.setResultCode("ACCOUNT_DISABLED");
                    response.setResultMessage("账户已被禁用");
                    response.setLoginResult(false);
                } else {
                    // 敏感信息处理，不返回密码
                    user.setUSERPASSWORD(null);
                    response.setUserInfo(user);
                    response.setResultCode("SUCCESS");
                    response.setResultMessage("登录成功");
                    response.setLoginResult(true);
                    response.setLoginTime(new java.util.Date().toString());
                }
            } else {
                response.setResultCode("AUTH_FAILED");
                response.setResultMessage("用户名或密码错误");
                response.setLoginResult(false);
            }
            
        } catch (Exception e) {
            response.setResultCode("ERROR");
            response.setResultMessage("登录验证失败: " + e.getMessage());
            response.setLoginResult(false);
        }
        
        return response;
    }
    
    @Override
    public UpdatePasswordResponse updatePassword(UpdatePasswordRequest request) {
        UpdatePasswordResponse response = new UpdatePasswordResponse();
        
        try {
            if (request == null || !StringUtils.hasText(request.getUserCode()) || 
                !StringUtils.hasText(request.getOldPassword()) || 
                !StringUtils.hasText(request.getNewPassword())) {
                response.setResultCode("ERROR");
                response.setResultMessage("请求参数不完整");
                response.setUpdateResult(false);
                return response;
            }
            
            // 验证旧密码
            User user = authenticateUser(request.getUserCode(), request.getOldPassword());
            if (user == null) {
                response.setResultCode("OLD_PASSWORD_ERROR");
                response.setResultMessage("旧密码错误");
                response.setUpdateResult(false);
                return response;
            }
            
            // 更新密码
            boolean success = updateUserPassword(request.getUserCode(), request.getNewPassword());
            
            if (success) {
                response.setResultCode("SUCCESS");
                response.setResultMessage("密码更新成功");
                response.setUpdateResult(true);
            } else {
                response.setResultCode("UPDATE_FAILED");
                response.setResultMessage("密码更新失败");
                response.setUpdateResult(false);
            }
            
        } catch (Exception e) {
            response.setResultCode("ERROR");
            response.setResultMessage("密码更新失败: " + e.getMessage());
            response.setUpdateResult(false);
        }
        
        return response;
    }
    
    @Override
    public GetUsersByDeptResponse getUsersByDept(GetUsersByDeptRequest request) {
        GetUsersByDeptResponse response = new GetUsersByDeptResponse();
        
        try {
            if (request == null || !StringUtils.hasText(request.getDeptCode())) {
                response.setResultCode("ERROR");
                response.setResultMessage("部门编码不能为空");
                return response;
            }
            
            // 这里实现根据部门查询用户的逻辑
            UserList userList = findUsersByDept(
                request.getDeptCode(),
                request.getUserStatus(),
                request.getPageSize() != null ? request.getPageSize() : 0,
                request.getPageNumber() != null ? request.getPageNumber() : 0
            );
            
            // 敏感信息处理，不返回密码
            if (userList != null && userList.getACCOUNT() != null) {
                for (User user : userList.getACCOUNT()) {
                    user.setUSERPASSWORD(null);
                }
            }
            
            response.setUsers(userList);
            response.setTotalCount(userList != null && userList.getACCOUNT() != null ? 
                                 userList.getACCOUNT().size() : 0);
            response.setResultCode("SUCCESS");
            response.setResultMessage("查询成功");
            
        } catch (Exception e) {
            response.setResultCode("ERROR");
            response.setResultMessage("查询失败: " + e.getMessage());
        }
        
        return response;
    }
    
    @Override
    public String testConnection() {
        return "User WebService is running successfully! Current time: " + new java.util.Date();
    }
    
    // 辅助方法
    private String validateUserData(User user) {
        if (!StringUtils.hasText(user.getUSERCODE())) {
            return "用户编码不能为空";
        }
        if (!StringUtils.hasText(user.getUSERNAME())) {
            return "用户姓名不能为空";
        }
        if (!StringUtils.hasText(user.getDEPTCODE())) {
            return "部门编码不能为空";
        }
        
        // 验证密级范围
        if (user.getSAFELEVEL() != null &&
            user.getSAFELEVEL() != 0 && user.getSAFELEVEL() != 10 &&
            user.getSAFELEVEL() != 20 && user.getSAFELEVEL() != 30) {
            return "密级编码无效，必须是0(公开)、10(内部)、20(秘密)、30(机密)";
        }
        
        // 验证性别
        if (StringUtils.hasText(user.getGENDER()) &&
            !"male".equalsIgnoreCase(user.getGENDER()) &&
            !"female".equalsIgnoreCase(user.getGENDER())) {
            return "性别必须是male或female";
        }
        
        return null;
    }
    
    private void processUserPassword(User user) {
        // 如果密码为空，设置默认密码
        if (!StringUtils.hasText(user.getUSERPASSWORD())) {
            user.setUSERPASSWORD(DEFAULT_PASSWORD);
        }
        
        // 这里可以添加密码加密逻辑
        // user.setUserpassword(passwordEncoder.encode(user.getUserpassword()));
    }
    
    private void addFailDetail(List<FailDetail> failDetails, User user, String errorMessage) {
        FailDetail detail = new FailDetail();
        detail.setUserCode(user.getUSERCODE());
        detail.setUserName(user.getUSERNAME());
        detail.setErrorMessage(errorMessage);
        failDetails.add(detail);
    }
    
    // 业务方法实现（需要根据实际业务实现）
    private boolean saveOrUpdateUser(User user) {
        // 实现保存或更新用户的业务逻辑
        // 这里可以连接数据库进行操作
        return true;
    }
    
    private User findUserByCode(String userCode) {
        // 实现根据用户编码查询用户的逻辑
        // 这里可以连接数据库进行查询
        return null;
    }
    
    private User authenticateUser(String userCode, String password) {
        // 实现用户认证逻辑
        // 这里可以连接数据库进行验证
        return null;
    }
    
    private boolean updateUserPassword(String userCode, String newPassword) {
        // 实现更新密码逻辑
        return true;
    }
    
    private UserList findUsersByDept(String deptCode, Integer userStatus, int pageSize, int pageNumber) {
        // 实现根据部门查询用户的逻辑
        UserList userList = new UserList();
        // 设置用户列表
        return userList;
    }
}